import React, { useState, useEffect } from 'react';
import { Row, Col, Statistic, Progress, Spin } from 'antd';
import { 
  ArrowUpOutlined, 
  ArrowDownOutlined, 
  FireOutlined, 
  TrophyOutlined,
  HeartOutlined,
  CalendarOutlined,
  BarChartOutlined
} from '@ant-design/icons';
import { WeightRecord, IndicatorData } from '../types';
import { WeightAPI } from '../services/api';

interface IndicatorPanelProps {
  refreshTrigger?: number;
}

const IndicatorPanel: React.FC<IndicatorPanelProps> = ({ refreshTrigger }) => {
  const [loading, setLoading] = useState(true);
  const [latestWeight, setLatestWeight] = useState<WeightRecord | null>(null);
  const [indicators, setIndicators] = useState<IndicatorData[]>([]);

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      const [latestResponse, indicatorsResponse] = await Promise.all([
        WeightAPI.getLatestWeight(),
        WeightAPI.getIndicators(30)
      ]);

      if (latestResponse.success && latestResponse.data) {
        setLatestWeight(latestResponse.data);
      }

      if (indicatorsResponse.success && indicatorsResponse.data) {
        setIndicators(indicatorsResponse.data);
      }
    } catch (error) {
      console.error('获取指标数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [refreshTrigger]);

  // 计算连续天数（从4月10日开始）
  const calculateConsecutiveDays = () => {
    if (!indicators || indicators.length === 0) return 0;
    const startDate = new Date('2025-04-10');
    const endDate = new Date('2025-08-30');
    const diffTime = Math.abs(endDate.getTime() - startDate.getTime());
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays + 1; // 包含起始日
  };

  // 计算BMI（身高180cm）
  const calculateBMI = () => {
    if (!latestWeight) return 0;
    const heightInMeters = 1.80; // 180cm
    const weightInKg = latestWeight.weight;
    return (weightInKg / (heightInMeters * heightInMeters));
  };

  // 计算目标完成度（目标90kg）
  const calculateTargetProgress = () => {
    if (!latestWeight || !indicators || indicators.length === 0) return 0;
    const startWeight = 95.5; // 起始体重
    const targetWeight = 90; // 目标体重
    const currentWeight = latestWeight.weight;
    const totalToLose = startWeight - targetWeight;
    const alreadyLost = startWeight - currentWeight;
    return Math.max(0, Math.min(100, (alreadyLost / totalToLose) * 100));
  };

  // 获取最新指标数据
  const latestIndicator = indicators && indicators.length > 0 ? indicators[0] : null;

  return (
    <div className="indicator-panel">
      <div className="section-header">
        <BarChartOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
        <span>数据指标</span>
      </div>

      <div className="indicators-grid">
        <div className="indicator-card">
          <div className="indicator-icon">⚖️</div>
          <div className="indicator-title">今日体重</div>
          <div className="indicator-value">
            {latestWeight ? `${latestWeight.weight}kg` : '--'}
          </div>
          <div className="indicator-change">
            {latestIndicator ? (
              <>
                <span style={{ color: (latestIndicator.weight_change_rate ?? 0) >= 0 ? '#ec0000' : '#00da3c' }}>
                  {(latestIndicator.weight_change_rate ?? 0) >= 0 ? '+' : ''}{(latestIndicator.weight_change_rate ?? 0).toFixed(1)}kg
                </span>
                <span style={{ color: (latestIndicator.weight_change_rate ?? 0) >= 0 ? '#ec0000' : '#00da3c', fontSize: '12px', marginLeft: '8px' }}>
                  ({(latestIndicator.weight_change_rate ?? 0) >= 0 ? '+' : ''}{Math.abs((latestIndicator.weight_change_rate ?? 0) / (latestWeight?.weight || 1) * 100).toFixed(1)}%)
                </span>
              </>
            ) : '--'}
          </div>
        </div>

        <div className="indicator-card">
          <div className="indicator-icon">🎯</div>
          <div className="indicator-title">目标完成度</div>
          <div className="indicator-value">
            {calculateTargetProgress().toFixed(1)}%
          </div>
          <div className="indicator-subtitle">目标: 90kg</div>
        </div>

        <div className="indicator-card">
          <div className="indicator-icon">📅</div>
          <div className="indicator-title">连续天数</div>
          <div className="indicator-value">
            {calculateConsecutiveDays()}
          </div>
          <div className="indicator-subtitle">4.10-8.30</div>
        </div>

        <div className="indicator-card">
          <div className="indicator-icon">📊</div>
          <div className="indicator-title">BMI指数</div>
          <div className="indicator-value">
            {calculateBMI().toFixed(1)}
          </div>
          <div className="indicator-subtitle">身高180cm</div>
        </div>

        <div className="indicator-card">
          <div className="indicator-icon">📈</div>
          <div className="indicator-title">最高体重</div>
          <div className="indicator-value" style={{ color: '#ec0000' }}>
            {latestIndicator?.highest_weight ? `${latestIndicator.highest_weight}kg` : '--'}
          </div>
          <div className="indicator-subtitle">历史最高</div>
        </div>

        <div className="indicator-card">
          <div className="indicator-icon">📉</div>
          <div className="indicator-title">最低体重</div>
          <div className="indicator-value" style={{ color: '#00da3c' }}>
            {latestIndicator?.lowest_weight ? `${latestIndicator.lowest_weight}kg` : '--'}
          </div>
          <div className="indicator-subtitle">历史最低</div>
        </div>
      </div>
    </div>
  );
};

export default IndicatorPanel;